package com.example.testservicebind;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    Boolean mBound = false;
    MyService mService;
    ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MyService.LocalBinder binder = (MyService.LocalBinder) service;
            mService = binder.getService234();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.id_btn_bind).setOnClickListener(this);
        findViewById(R.id.id_btn_unbind).setOnClickListener(this);
        findViewById(R.id.id_btn_servicecall).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.id_btn_bind:
                //    public abstract boolean bindService(@RequiresPermission Intent service,
                //            @NonNull ServiceConnection conn, @BindServiceFlags int flags);
                if (!mBound) {
                    bindService(new Intent(MainActivity.this, MyService.class), mConn, Context.BIND_AUTO_CREATE);
                }
                break;
            case R.id.id_btn_unbind:
                if (mBound) {
                    unbindService(mConn);
                    mBound = false;
                }
                break;
            case R.id.id_btn_servicecall:
                if (mBound) {
                    int num = mService.getRandomNumber();
                    LogUtil.printLog("MyService.getRandomNumber:" + num);
                }
                break;
        }
    }
}
